import React, { useEffect, useState } from 'react';
import { Form } from 'antd';
import { ShowDatePicker, ShowTimePicker } from '../index';
import moment from 'moment';
import styles from './index.less';

interface IProps {
  /**
   * 选择事件
   */
  onChange?: (values: { declarationStartTime: string; declarationEndTime: string }) => void;
  /**
   * 选择值
   */
  value?: {
    declarationStartTime: string;
    declarationEndTime: string;
  };
}

const DateAndTimePicker = (props: IProps) => {
  const { onChange, value: _value } = props;
  const [date, setDate] = useState<moment.Moment>();
  const [time, setTime] = useState<[moment.Moment, moment.Moment]>();

  useEffect(() => {
    if (_value) {
      const newDate = moment(_value?.declarationStartTime);
      const newTime =
        _value?.declarationStartTime && _value?.declarationEndTime
          ? [moment(_value?.declarationStartTime), moment(_value?.declarationEndTime)]
          : undefined;
      setDate(newDate);
      setTime(newTime);
    }
  }, [_value]);

  const _onChange = (data: { declarationStartTime: string; declarationEndTime: string }) => {
    onChange && onChange(data);
  };

  const onChangeDatePicker = (e: any) => {
    if (e && time) {
      const data = {
        declarationStartTime: `${moment(e).format('YYYY-MM-DD')} ${
          time && time[0] ? moment(time[0]).format('HH:mm:ss') : ''
        }`,
        declarationEndTime: `${moment(e).format('YYYY-MM-DD')} ${
          time && time[1] ? moment(time[1]).format('HH:mm:ss') : ''
        }`,
      };
      _onChange(data);
    }
    setDate(e);
  };

  const onChangeTimePicker = (e: any) => {
    if (date && e) {
      const data = {
        declarationStartTime: `${moment(date).format('YYYY-MM-DD')} ${
          e && e[0] ? moment(e[0]).format('HH:mm:ss') : ''
        }`,
        declarationEndTime: `${moment(date).format('YYYY-MM-DD')} ${
          e && e[1] ? moment(e[1]).format('HH:mm:ss') : ''
        }`,
      };
      _onChange(data);
    }
    setTime(e);
  };

  return (
    <div className={styles.container}>
      <Form.Item style={{ marginBottom: 0 }}>
        <ShowDatePicker
          value={date}
          format="YYYYMMDD"
          placeholder="请选择日期"
          onChange={onChangeDatePicker}
        />
      </Form.Item>
      <Form.Item style={{ marginBottom: 0 }}>
        <ShowTimePicker
          type="rangePicker"
          value={time}
          format="HHmm"
          placeholder={['开始时间', '结束时间']}
          onChange={onChangeTimePicker}
        />
      </Form.Item>
    </div>
  );
};

export default DateAndTimePicker;
